package org.spring.mqtt.config;

import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MQTTBeanConfig {
    @Value("${mqtt.apiKey}")
    private String apiKey;
    @Value("${mqtt.secretKey}")
    private String secretKey;
    @Value("${mqtt.broker}")
    private String broker;
    @Value("${mqtt.clientId}")
    private String clientId;

    @Value("${mqtt.userName:}")
    private String userName;

    @Value("${mqtt.password:}")
    private String password;

    @Value("${mqtt.keepAliveInterval:2000}")
    private Integer keepAliveInterval;

    @Bean
    @SneakyThrows
    public MqttClient getMqttClient(){
        return new MqttClient(broker,clientId,new MemoryPersistence());
    }

    @Bean
    public MqttConnectOptions getMqttConnectOptions(){
        MqttConnectOptions mqttConnectOptions=new MqttConnectOptions();
        mqttConnectOptions.setKeepAliveInterval(keepAliveInterval);
        if (StringUtils.isNotEmpty(userName)){
            mqttConnectOptions.setUserName(userName);
        }
        if (StringUtils.isNotEmpty(password)){
            mqttConnectOptions.setPassword(password.toCharArray());
        }
        return mqttConnectOptions;
    }
}
